<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" style="width: 200px" placeholder="请选择状态" clearable>
          <el-option v-for="dict in update_order" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="类别" prop="labels">
        <el-input v-model="queryParams.labels" placeholder="请输入类别" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="创建时间" prop="createdAt">
        <el-date-picker
          clearable
          v-model="queryParams.createdAt"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="collectorOrderList" border stripe>
      <el-table-column
        label="订单唯一编号"
        align="center"
        prop="orderNo"
        width="210"
        v-if="columns[1].visible"
        :show-overflow-tooltip="true">
        <template #default="scope">
          <el-button @click="handleUpdate(scope.row)" type="text">{{ scope.row.orderNo }}</el-button>
        </template>
      </el-table-column>
      <el-table-column
        label="客户"
        align="center"
        prop="clientId"
        v-if="columns[2].visible"
        :show-overflow-tooltip="true" />
      <el-table-column
        label="重量"
        align="center"
        prop="weight"
        v-if="columns[3].visible"
        :show-overflow-tooltip="true" />
      <el-table-column
        label="价值"
        align="center"
        prop="totalValue"
        v-if="columns[4].visible"
        :show-overflow-tooltip="true" />
      <el-table-column label="状态" align="center" prop="status" v-if="columns[5].visible">
        <template #default="scope">
          <dict-tag :options="update_order" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="图片" align="center" prop="images" width="100" v-if="columns[6].visible">
        <template #default="scope">
          <image-preview :src="scope.row.images" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column
        label="置信度"
        align="center"
        prop="confidence"
        v-if="columns[7].visible"
        :show-overflow-tooltip="true">
        <template #default="scope">{{ (scope.row.confidence - 0).toFixed(2) }}</template>
      </el-table-column>
      <el-table-column
        label="类别"
        align="center"
        prop="labels"
        v-if="columns[8].visible"
        :show-overflow-tooltip="true" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createdAt"
        width="100"
        v-if="columns[9].visible"
        :show-overflow-tooltip="true">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        prop="updatedAt"
        width="100"
        v-if="columns[10].visible"
        :show-overflow-tooltip="true">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updatedAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="订单地址"
        align="center"
        prop="address"
        v-if="columns[11].visible"
        :show-overflow-tooltip="true" />
      <el-table-column width="120" label="距离" align="center" prop="distance" v-if="columns[12].visible">
        <template #default="scope">{{ (scope.row.distance - 0).toFixed(2) }}km</template>
      </el-table-column>
      <el-table-column label="操作" width="215" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['order:collectorOrder:edit']"
            >接单</el-button
          >
          <el-button
            link
            type="primary"
            icon="Star"
            @click="handleFinish(scope.row)"
            v-hasPermi="['order:collectorOrder:remove']"
            >已完成</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <el-dialog :title="title" v-model="open" width="500px" append-to-body destroyOnClose>
      <el-form ref="collectorOrderRef" :model="form" :rules="rules" label-width="80px" style="margin-bottom: 30px">
        <el-form-item label="地址" prop="locationStr">
          <el-input v-model="form.locationStr" placeholder="请输入地址" />
        </el-form-item>
      </el-form>
      <t-map
        :disabled="true"
        :navigation="{
          current: currentLocation,
          destination: { lat: form.latitude, lng: form.longitude }
        }" />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="CollectorOrder">
import { finishCollectorOrder, listCollectorOrder, updateCollectorOrder } from '@/api/order/collectorOrder'
import useUserStore from '@/store/modules/user'
const { proxy } = getCurrentInstance()
const { update_order } = proxy.useDict('update_order')
import TMap from '@/components/TMap/index.vue'
import { ref, watch } from 'vue'
import { getGeoCoder, getLocation } from '../../../api/map'

const collectorOrderList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const total = ref(0)
const title = ref('')
const userStore = useUserStore()
const currentLocation = ref(null)

const data = reactive({
  form: {
    locationStr: null,
    latitude: null,
    longitude: null
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    status: null,
    labels: null,
    createdAt: null
  },
  //表格展示列
  columns: [
    { key: 0, label: '', visible: true },
    { key: 1, label: '订单唯一编号', visible: true },
    { key: 2, label: '客户', visible: true },
    { key: 3, label: '重量', visible: true },
    { key: 4, label: '价值', visible: true },
    { key: 5, label: '状态', visible: true },
    { key: 6, label: '图片', visible: true },
    { key: 7, label: '置信度', visible: true },
    { key: 8, label: '类别', visible: true },
    { key: 9, label: '创建时间', visible: true },
    { key: 10, label: '更新时间', visible: true },
    { key: 11, label: '订单地址', visible: true },
    { key: 12, label: '距离', visible: true }
  ]
})

const { queryParams, form, rules, columns } = toRefs(data)

watch(
  () => form.value.locationStr,
  newValue => {
    handleLocationChange(newValue)
  }
)
/** 查询接取订单列表 */
function getList() {
  loading.value = true
  getLocation(import.meta.env.VITE_APP_MAP_KEY).then(res => {
    currentLocation.value = res.data.result.location
    listCollectorOrder({
      ...queryParams.value,
      userLongitude: res.data.result.location.lng,
      userLatitude: res.data.result.location.lat
    }).then(response => {
      collectorOrderList.value = response.rows
      total.value = response.total
      loading.value = false
    })
  })
}
function handleLocationChange(value) {
  if (value) {
    getGeoCoder(import.meta.env.VITE_APP_MAP_KEY, 'address', value)
      .then(res => {
        currentLocation.value = res.data.result.location
      })
      .catch(err => {
        proxy.$modal.msgError('地址解析失败')
      })
  }
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    orderId: null,
    orderNo: null,
    clientId: null,
    collectorId: null,
    weight: null,
    unitPrice: null,
    totalValue: null,
    status: null,
    images: null,
    confidence: null,
    labels: null,
    createdAt: null,
    updatedAt: null,
    address: null
  }
  proxy.resetForm('collectorOrderRef')
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef')
  handleQuery()
}

/** 接取按钮操作 */
function handleUpdate(row) {
  reset()
  form.value = {
    ...row
  }
  form.value.address = row.address
  form.value.longitude = row.longitude
  form.value.latitude = row.latitude
  form.value.collectorId = userStore.id
  form.value.status = 'accepted'
  open.value = true
  title.value = '接取订单'
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs['collectorOrderRef'].validate(valid => {
    if (valid) {
      if (form.value.orderId != null) {
        updateCollectorOrder(form.value).then(response => {
          proxy.$modal.msgSuccess('接单成功')
          open.value = false
          getList()
        })
      }
    } else {
      proxy.$modal.msgError('表单校验失败!')
    }
  })
}
/** 完成按钮操作 */
function handleFinish(row) {
  const _orderIds = row.orderId || ids.value
  proxy.$modal
    .confirm('订单是否完成？')
    .then(() => {
      return finishCollectorOrder({
        orderId: _orderIds,
        status: 'completed'
      })
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('订单完成！')
    })
    .catch(() => {})
}
getList()
</script>
